package com.mec.web.y2012.coreservlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import org.apache.log4j.Logger;

public class EchoServer extends NetworkServer {

	private int maxRequestLines = 50;
	private String serverName = "EchoServer";
	
	//
	public EchoServer(int port, int maxConnections) {
		super(port, maxConnections);
	}
	

	@Override
	protected void handleConnection(Socket server) throws IOException{
		logger.info(serverName + ":got connection from " +
				server.getInetAddress().getHostAddress()
				);
		//
		BufferedReader in = SocketUtil.getReader(server);
		PrintWriter out = SocketUtil.getWriter(server);
		//
		String[] inputLines = new String[maxRequestLines];
		
		int i = 0 ;
		for(; i<maxRequestLines; ++i){
			inputLines[i] = in.readLine();
			//
			if(null == inputLines[i]){
				break;
			}
			if(inputLines[i].isEmpty()){
				if(usingPost(inputLines)){
					readPostData(inputLines, i, in);
					i += 2;
				}
				break;
			}
		}
		//
		printHeader(out);
		for(int j = 0 ; j <i ; ++j){
			String inputLine = inputLines[j];
			out.println(inputLine);
		}
		//
		printTrailer(out);
		server.close();
	}
	
	private boolean usingPost(String[] inputLines){
		return inputLines[0].toUpperCase().startsWith("POST");
	}
	
	private void readPostData(String[] inputLines, int i, BufferedReader in) throws IOException{
		int contentLength = contentLength(inputLines);
		char[] postData = new char[contentLength];
		in.read(postData, 0, contentLength);
		inputLines[++i] = new String(postData, 0, contentLength);
	}
	
	private int contentLength(String[] inputs){
		String input;
		for(int i = 0 ; i<inputs.length; ++i){
			if(inputs[i].isEmpty()){
				break;
			}
			input = inputs[i].toUpperCase();
			if(input.startsWith("CONTENT-LENGTH")){
				return getLength(input);
			}
		}
		return 0;
	}
	private int getLength(String lengthStr){
		String[] tokenizer = lengthStr.split("\\s+");
		return Integer.parseInt(tokenizer[1]);
	}
	private void printHeader(PrintWriter out){
		out.println("HTTP/1.0 200 OK\r\n" +
				"Server: " + serverName +"\r\n" +
				"Content-Type: text/html\r\n" +
				"\r\n" +
				Constants.docType +
				"<html>\n<head>\n<title>" + serverName + " Results</title>\n" +
				"</head>\n\n<body><h1>" +serverName +"</h1><hr/>" +
				"<p>Here is the request line and request headers\n sent by your browser:\n</p><pre>"
				);
		
	}
	
	private void printTrailer(PrintWriter out){
		out.println("</pre>\n</body>\n</html>");
	}
	
	private static final Logger logger = 
			Logger.getLogger(EchoServer.class);
}
